package com.zlyx.easy.http.handlers;

import java.util.Map.Entry;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.zlyx.easy.core.annotations.Brancher;
import com.zlyx.easy.core.tool.Ops;
import com.zlyx.easy.http.models.RequestModel;

/**
 * 
 * @Auth 赵光
 * @Describle
 * @2019年12月25日
 */
@Brancher(todo = { "处理post请求" }, value = "POST")
public class PostMappingHandler extends AbstractMappingHandler {

	@Override
	public Object handleMapping(String url, RequestModel rm) {
		MultiValueMap<String, String> re = new LinkedMultiValueMap<>();
		String key = null;
		String value = null;
		for (Entry<String, Object> entry : rm.getParams().entrySet()) {
			if (entry.getValue() != null) {
				key = entry.getKey();
				value = "" + entry.getValue();
				if (url.contains(":" + key)) {
					url = url.replaceAll(":" + key, "" + value);
				} else if (url.contains("{" + key + "}")) {
					url = url.replaceAll("{" + key + "}", "" + value);
				} else {
					re.add(key, value);
				}
			}
		}
		url = handleIpAndPort(url, rm);
		Ops.getLogger(rm.getCls()).info("请求【{}】POST 地址：{}, 参数是 {}", rm.getId(), url, re.toSingleValueMap());
		Object response = restTemplate.postForObject(url, re, rm.getReturnType());
		Ops.getLogger(rm.getCls()).info("请求【{}】POST 结果：{}", rm.getId(), response);
		return response;
	}
}
